<template>
  <div class="live-detail">
    <el-row class="live-layout">
      <!-- 左侧视频区域 -->
      <el-col :span="18" class="video-container">
        <div  style="border-radius: 20px;height: 60px;padding: 0 20px;width: 100%;">
          <el-avatar
            shape="circle"
            size="32"
            src="https://vue.ruoyi.vip/static/img/profile.473f5971.jpg"
            class="avatar" style="margin-top: 10px;float: left;width: 32px;height: 32px;"
          />
          <div style="color: white;float: left;font-size: 12px;margin-top: 10px;margin-left: 10px;">
          <p style="float: left;" >{{this.room.userName}}</p>
          <el-button style="float: left;margin-top: 5px;margin-left: 5px;" type="danger" size="mini" @click="updateCollect(true)" v-if="!this.room.collect" icon="el-icon-check" round>关注</el-button>
          <el-button style="float: left;margin-top: 5px;margin-left: 5px;" type="info" size="mini" @click="updateCollect(false)" v-if="this.room.collect" icon="el-icon-close" round>取关</el-button>
        </div>
        </div>
        <!-- <div style="float: left;width: 100%;height: 753px;" v-show="!this.roomState">
          <el-empty description="未开播" ></el-empty>
        </div> -->
      
        <div style="float: left;width: 100%;height: 753px;" >
          <div id="video-player" class="video-player" ></div>
        </div>

      <div class="live-container" style="float: left;height: 60px;width: 100%;
    padding: 0px 20px;">
        <!-- 送礼物 -->
      
    <div class="block" style="float: left;height: 60px;width: 60px;margin-left: 30px;" v-for="(gift, index) in giftList" :key="index">
            <el-image @click="sendMessage(2,gift.name)"
          style="width: 40px; height: 40px;float: left;"
          :src="gift.image"
          ></el-image>
        <span class="demonstration" style="height: 20px;width: 40px;float: left;font-size:12px; color: white">{{gift.name}}</span>
      </div>

        <!-- 礼物特效全屏展示 -->
        <div class="gift-overlay">
          <div
            class="gift-item"
            v-for="(gift, index) in gifts"
            :key="index"
            @animationend="removeGift(index)"
          >
            <img :src="gift.image" :alt="gift.name" class="gift-image" />
          </div>
        </div>
      </div>
      </el-col>


      <!-- 右侧聊天区域 -->
      <el-col :span="6" >
        <div class="chat-container">
            <!-- 在线观众 -->
            <div style="padding: 20px 00px 0px 20px;" @click="onDialogTableVisible">
              <el-link icon="el-icon-user-solid"><span style="font-size: 14px;">在线观众 · {{this.roomCount}}</span></el-link>
            </div>

          <!-- 聊天记录展示 -->
          <el-scrollbar class="chat-history" wrap-style="overflow-x:hidden;">
        
            <div v-for="(message, index) in uniqueSortedMessages" :key="message.id" class="chat-message">
              <div v-if="message.type==1">
                <span class="username">{{ message.userName }}：</span>
                <span class="content">{{ message.body }}</span>
              </div>
              <div v-if="message.type==2">
                <span class="username">{{ message.userName }}：</span>
                <span class="content" style="color: #eba825;">送出了 <img 
                    style="width: 16px; height: 16px;"
                    :src="getGiftUrl(message.body)"
                    /> × 1
                  </span>
              </div>
            </div>
          </el-scrollbar>

          <!-- 用户上线 -->
          <div style="padding-left: 20px;"  v-show="this.onlineUser!=''">
            <span  class="username">{{onlineUser}} </span><span class="content">来了</span>
          </div>
          <!-- 输入框和发送按钮 -->
          <div class="chat-input-area" @keyup.enter="sendMessage(1,inputMessage)" style="border-radius: 10px;margin: 10px;">
            <el-input
              v-model="inputMessage" maxlength="20"
              show-word-limit
              :placeholder="!this.$store.state.user.loginStatus?'请先登录':'与大家互动一下'"
              rows="2"
              :disabled="!this.$store.state.user.loginStatus"
              class="chat-input"
              
            ></el-input>

            <el-avatar v-if="this.$store.state.user.loginStatus"
            @click.native="toggleEmojiPicker"
            size="medium"
            :src="localImagePath"
            style="margin-right: 10px;"
          />

            <!-- 表情选择器 -->
            <div v-if="showEmojiPicker" class="emoji-picker">
              <Picker @select="addEmoji" />
            </div>

            <!-- 发送按钮 -->
            <el-button v-if="this.$store.state.user.loginStatus"
            type="success" icon="el-icon-top" circle size="medium"
              @click="sendMessage(1,inputMessage)"
            >
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 在线观众弹框 -->
    <el-dialog title="在线观众" :visible.sync="dialogTableVisible" :close-on-click-modal="false" width="30%">
    <el-table :data="gridData" 
    height="400">
      <el-table-column  label="序号" type="index" width="100"></el-table-column>
      <el-table-column property="userName" label="姓名" width="300"></el-table-column>
    </el-table>
  </el-dialog>

  </div>
</template>

<script>
// 在需要的页面引入

import 'xgplayer';
import hlsjsPlayer from 'xgplayer-hls.js';
import { Picker } from 'emoji-mart-vue';
import { getUserUniqueId } from '@/utils/uniqueId';
import { chat,getRoomInfo,updateCollect,getUserRoomList } from '@/api/room'
import { parseTime } from '@/utils/ruoyi';
import wxpng from '@/assets/wx.png';

export default {
  components: {
    Picker,
  },
  data() {
    return {
      roomId:this.$route.query.roomId,//房间id
      room:{},//房间信息
      chatMessages: [],//消息记录
      inputMessage: '',//发送消息内容
      showEmojiPicker: false,
      lastMsgTime: 0,//最新消息时间 默认0拉取全部
      wsUrl: "ws://127.0.0.1:5000/ws",//websocket服务器地址
      ws: null,
      gifts: [], // 礼物队列
      roomCount:0, //直播间人数
      onlineUser: "", // 用户上线
      localImagePath: wxpng,
      dialogTableVisible:false,//在线观众弹框
      gridData: [], // 用户列表
      giftList: [
        {
          name: '小心心', image: 'https://p3-webcast.douyinpic.com/img/webcast/7ef47758a435313180e6b78b056dda4e.png~tplv-obj.png'
        },
        {
          name: '人气票', image: 'https://p3-webcast.douyinpic.com/img/webcast/e9b7db267d0501b8963d8000c091e123.png~tplv-obj.png'
        },
        {
          name: '墨镜', image: 'https://p3-webcast.douyinpic.com/img/webcast/eee04e798ad7f08c9faf577f52e258f9.png~tplv-obj.png'
        },
        {
          name: '鲜花', image: 'https://p3-webcast.douyinpic.com/img/webcast/42d4cd329e5c01be43c3432567847507.png~tplv-obj.png'
        },
        {
          name: '跑车', image: 'https://p3-webcast.douyinpic.com/img/webcast/a44104d2d61cc1868495ea9a58ced24f.png~tplv-obj.png'
        },
        {
          name: '棒棒糖', image: 'https://p11-webcast.douyinpic.com/img/webcast/2756f07818a73a8c79f024e959665110.png~tplv-obj.png'
        },
        {
          name: '大啤酒', image: 'https://p11-webcast.douyinpic.com/img/webcast/71801c53df3977b1470ac2afb8250ac1.png~tplv-obj.png'
        },
        {
          name: '玫瑰', image: 'https://p11-webcast.douyinpic.com/img/webcast/96e9bc9717d926732e37351fae827813.png~tplv-obj.png'
        },
        {
          name: '抖音', image: 'https://p11-webcast.douyinpic.com/img/webcast/802a21ae29f9fae5abe3693de9f874bd~tplv-obj.png'
        },
        {
          name: '烟花', image: 'https://p11-webcast.douyinpic.com/img/webcast/1e6eb994c0b5be0264300cf63a146eb8.png~tplv-obj.png'
        },
        {
          name: '比心', image: 'https://p11-webcast.douyinpic.com/img/webcast/cdcbcb5aac6b81c5becb69cfe8589100.png~tplv-obj.png'
        },
        {
          name: '嘉年华', image: 'https://p11-webcast.douyinpic.com/img/webcast/c32f9ccf5304824dd050d6e77536a4ab.png~tplv-obj.png'
        },
        {
          name: '热气球', image: 'https://p11-webcast.douyinpic.com/img/webcast/0e176c2d0ac040ae0cad13d100f61b02.png~tplv-obj.png'
        },
        {
          name: '加油鸭', image: 'https://p11-webcast.douyinpic.com/img/webcast/c169b7ff42cb389d73878e87594c7846.png~tplv-obj.png'
        },
      ]
    };
  },
  created() {
    //初始化websocker
    this.initWs();
    //查询详情
    this.getRoomInfo();
    // 定时检查是否超过 25 秒没有发送消息 就定时拉取消息,也相当于心跳检测
    setInterval(() => {
      console.log('定时拉取消息：'+parseTime(Date.now()));
      this.ws.send(JSON.stringify({"type":1,"data":this.lastMsgTime}));
    }, 30000);
    // 定时查询直播间人数
    setInterval(() => {
      console.log('定时查询直播间人数：'+parseTime(Date.now()));
      this.onlineUser="";
      this.ws.send(JSON.stringify({"type":2}));
    }, 10000);
  },
  beforeDestroy() {
    // 组件销毁前关闭WebSocket连接
    if (this.ws) {
      this.ws.close();
    }
  },
  mounted(){
    // 初始化视频播放器
    this.initPlayer();
  },
  computed: {
    uniqueSortedMessages() {
      // 使用 Set 来去重消息，避免重复的 id
      const seen = new Set();
      const uniqueMessages = this.chatMessages.filter(message => {
        
        if (seen.has(message.id)) {
          return false; // 如果 id 已经存在，跳过这条消息
        } else {
          seen.add(message.id); // 添加 id 到 Set 中
          return true;
        }
      });
      // 根据 id 排序（升序）
      return uniqueMessages.sort((a, b) => a.id - b.id);
    }
  },
  methods: {
    sendGift(giftName) {
      this.gifts.push(this.giftList.find(gift => gift.name === giftName));
    },
    getGiftUrl(body){
      return this.giftList.find(gift => gift.name === body).image;
    },
    removeGift(index) {
      this.gifts.splice(index, 1);
    },
    getRoomInfo() {
      getRoomInfo(this.roomId).then(res => {
          this.room=res.data;
        }).catch(error => {
        })
    },
    onDialogTableVisible(){
        this.dialogTableVisible = true;
        getUserRoomList(this.roomId).then(res => {
          this.gridData=res.data;
        }).catch(error => {
        })
    },
    initPlayer() {
      const player = new hlsjsPlayer({
        container: document.getElementById('video-player'),
        url: "http://localhost:5000/media/hls/m3u8?roomId="+this.roomId, // 替换为你的 HLS 流地址
        id: 'video-player', // 上面容器的id选择器
        autoplay: true, // 自动播放
        fluid: true, // 自动适应父容器宽高
        cssFullscreen: true, // 启用 CSS 全屏适配
        lang: 'zh-cn', // 设置语言，可选
        volume: 0.5, // 默认音量
      });
    },
    initWs() {
      const wsuri = this.wsUrl+"?user_unique_id="+getUserUniqueId()+"&room_id="+this.roomId;
      this.ws = new WebSocket(wsuri);
      const self = this;
      // 连接监听
      this.ws.onopen = function (event) {
        console.log('连接监听');
        //拉取历史聊天记录
        self.ws.send(JSON.stringify({"type":1,"data":self.lastMsgTime}));
        //拉取直播间人数
        self.ws.send(JSON.stringify({"type":2}));
      };
      // 接收消息监听
      this.ws.onmessage = function (event) {
        console.log('接收消息监听：'+parseTime(Date.now()));
        const data = JSON.parse(event.data);
        if(data.type===1){
          // 重新拉取消息
          const data = {"type":1,"data":self.lastMsgTime};
          self.ws.send(JSON.stringify(data));
        }else if(data.type===3){
          // 查询到直播间人数
          self.roomCount=data.data;
        }else{
          // 查询到聊天记录
          for (let i = 0; i < data.data.length; i++) {
            const dataObj = JSON.parse(data.data[i]);
            //如果等于2就送礼物特效
            if(dataObj.type===2){
              self.sendGift(dataObj.body)
              self.chatMessages.push(dataObj);
            }else if(dataObj.type===3){
              //if (self.onlineUser!='') {
                //用户上线
                self.onlineUser=dataObj.userName;
                // setTimeout(() => {
                //   self.onlineUser = '';
                // }, 1500);
              //}
            }else{
              self.chatMessages.push(dataObj);
            }
            // 判断 sendTime 是否更大，如果是，则更新 latestItem
            if (dataObj.sendTime > self.lastMsgTime) {
                self.lastMsgTime = dataObj.sendTime;
            }
          }
          self.scrollToBottom();
        }
      };
      // 关闭连接监听
      this.ws.onclose = function (event) {
        console.log('关闭连接监听');
        if (this.ws) {
          this.ws.close();
          this.ws = null;
        }
      };
    },
    // 发送消息
    sendMessage(type,body) {
      if (body) {
        console.log('聊天内容：'+body)
        const data = {roomId:this.roomId+"",type:type,body:body.trim()};
        chat(data).then(res => {
          this.chatMessages.push(res.data);
          if(type===1){
            this.inputMessage = '';
          }
          this.scrollToBottom();
        }).catch(error => {
        })
      }
    },
    //用户关注和取关
    updateCollect(bCollect){
      updateCollect(this.roomId,bCollect).then(res => {
          this.$message.success("操作成功");
          this.getRoomInfo();
        }).catch(error => {
        })
    },
    // 滚动到聊天记录底部
    scrollToBottom() {
      this.$nextTick(() => {
        const chatHistory = this.$el.querySelector('.chat-history .el-scrollbar__wrap');
        chatHistory.scrollTop = chatHistory.scrollHeight;
      });
    },
    // 切换表情选择器显示
    toggleEmojiPicker() {
      this.showEmojiPicker = !this.showEmojiPicker;
    },
    // 添加表情到输入框
    addEmoji(emoji) {
      this.inputMessage += emoji.native;
      this.showEmojiPicker = false;
    },
  },
};
</script>

<style scoped>
.live-detail {
  height: calc(100vh - 60px);
  background-color: #f0f0f0;
}

.live-layout {
  height: 100%;
}

.video-container {
  height: calc(100vh - 80px);
  border-radius: 20px;
  background: #333333;
  position: relative; /* 确保子元素可以绝对定位 */
}

.video-player {
  width: 100%;
  position: absolute; /* 保证播放器的位置为绝对定位 */
}
.chat-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 80px);
  /* background-color: white; */
  /* border: 1px solid #dcdcdc; */
  /* border-radius: 10px; */
}

.chat-history {
  flex: 1;
  padding: 20px;
  /* background-color: #ffffff; */
}

.chat-message {
  margin-bottom: 8px;
  line-height: 1.5;
}

.username {
  font-weight: bold;
  color: #409eff;
}

.content {
  color: #333333;
}

.chat-input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #dddde2;
}

.chat-input {
  flex: 1;
  margin-right: 10px;
}

.emoji-button {
  margin-right: 10px;
}
::v-deep .el-icon-my-message {
        background: url('@/assets/wx.png') center no-repeat;
        width: 32px;
        height: 32px;
}

.emoji-picker {
  position: absolute;
  bottom: 60px;
  right: 20px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
/* 主容器 */
.live-container {
  padding: 20px;
  text-align: center;
}

/* 全屏礼物特效区域 */
.gift-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: none; /* 防止干扰其他操作 */
  overflow: hidden;
}

/* 礼物特效 */
.gift-item {
  position: absolute;
  animation: fly-effect 3s ease-in-out forwards;
  opacity: 1;
}

/* 礼物图片样式 */
.gift-image {
  width: 100px; /* 调整礼物图片大小 */
  height: 100px;
}

/* 动画效果 */
@keyframes fly-effect {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  50% {
    transform: translate(-50%, -150%) scale(1.5);
    opacity: 0.8;
  }
  100% {
    transform: translate(-50%, -300%) scale(0.8);
    opacity: 0;
  }
}


</style>
